import { loginApi, getLoginInfoApi } from "@/api";
import { defineStore } from "pinia";
import { saveToken, removeToken } from "@/utils/token";
import { getToken } from "../utils/token";

export const useUserStore = defineStore({
  id: "app-user",

  // {"userId":"0e635f9be79644f99c4c02baad33a0a7","username":"test10001","realName":"test10001","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1wiaWRcIjpcIjBlNjM1ZjliZTc5NjQ0Zjk5YzRjMDJiYWFkMzNhMGE3XCIsXCJ0eXBlXCI6XCIxXCJ9IiwiaXNzIjoiaXNzdWVyIiwiZXhwIjoxNjg2MTQxNjQ0LCJpYXQiOjE2ODU1MzY4NDR9.KQFZyHLNO4_FNMKx_w_l445EsORIWevJgh8jOBvHdLk","homePath":"/dashboard/index","companyId":"567a54d725b444f6bb6e3dfc3d4211a0","catId":"1","roles":[{"roleName":"企业角色","value":"company"}]}

  state: () => ({}),

  getters: {

  },

  actions: {
    /**
     * 登录
     */
    async login(form: any) {
      try {
        const { token, expiratDate } = await loginApi(form);
        saveToken(token, expiratDate);
      } catch (ex) {
        uni.showToast({
          title: "用户名或密码错误",
          icon: "none",
        });
        return;
      }

      try {
        const res = await getLoginInfoApi();
        this.userInfo = { ...res };

        // uni.reLaunch({
        //   url: "/pages/tabbar/index",
        // });
      } catch (ex) {
        console.log(ex);
        uni.showToast({
          title: "用户信息获取失败",
          icon: "none",
        });
      }

      // if (res.roles.some((s) => s.value == "supervise")) {
      //   uni.reLaunch({
      //     url: "/pages/home2/index",
      //   });
      // } else {
      //   uni.reLaunch({
      //     url: "/pages/home/index",
      //   });
      // }
    },

    /**
     * 刷新用户信息
     */
    async checkUserInfo() {
      try {
        if (!getToken()) {
          uni.reLaunch({
            url: "/pages/login/index",
          });
          return;
        }
        const res = await getLoginInfoApi();
        this.userInfo = { ...res };
      } catch (ex) {
        console.log("获取用户信息异常", ex);

        uni.reLaunch({
          url: "/pages/login/index",
        });
      }
    },


  },
});
